package com.desiy.controller;


import com.desiy.pojo.entity.Books;
import com.desiy.service.BooksService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * @author Desiy
 * @date 2020/5/30 15:37
 */
@Controller
public class BooksController {

    @Resource
    private BooksService booksService;

    @RequestMapping("/")
    String index(){
        return "index";
    }
    @RequestMapping("/listAll")
    String list(Model model){
        Collection<Books> list = booksService.queryAll();
        model.addAttribute("list",list);
        return "books/list";
    }
    @GetMapping("/addPage")
    String addPage(){
        return "books/add";
    }
    @PostMapping("/add")
    String add(Books book){
        booksService.insert(book);
        return "redirect:/listAll";
    }
    @GetMapping("/updatePage/{id}")
    String updatePage(@PathVariable("id") Integer id,Model model){
        Books book = booksService.queryById(id);
        model.addAttribute("book",book);
        return "books/update";
    }
    @PostMapping("/update")
    String update(Books books){
        booksService.update(books);
        return "redirect:/listAll";
    }
    @RequestMapping("/delete/{id}")
    String delete(@PathVariable("id") Integer id){
        booksService.deleteById(id);
        return "redirect:/listAll";
    }
    @RequestMapping("query")
    String query(String queryName,Model model){
        Books book = booksService.queryByName(queryName);
        List<Books> list = new ArrayList<>();
        list.add(book);
        if (book == null){
            list = (List<Books>) booksService.queryAll();
            model.addAttribute("error","未找到该书籍。");
        }
        model.addAttribute("list",list);
        return "books/list";//如果是查询，我们只需显示查询结果。
    }
}
